<?php

namespace app\common\service\ai;

use Exception;
use think\facade\Db;
use app\common\service\CommonService;
use app\library\Date;

/**
 * 音色
 */
class SpeakerService extends CommonService {

    /**
     * 表名
     * @static string
     */
    protected static $table = 'speaker';

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getList() {
        return self::query(self::$table)->_equal('member_id')->order('id desc')->_select();
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListByAdmin($data) {
        $list = self::query(self::$table)->order('id desc')->_page(true);
        return $list;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListByHome($data) {
        $list = self::query(self::$table)->_equal('member_id')->order('id desc')->_page(true);
        return $list;
    }

    /**
     * 详情
     * @param array $data 数据
     * @return array
     */
    public static function getDetail($data) {
        return self::query(self::$table)->where(['id' => self::ID($data)])->_find();
    }

    /**
     * 详情
     * @param array $data 数据
     * @return array
     */
    public static function getDetailByAdmin($data) {
        return self::query(self::$table)->where(['id' => self::ID($data)])->_find();
    }

    /**
     * 训练
     * @param array $data 数据
     * @return mixed
     */
    public static function train($data) {
        Db::startTrans();
        // 音色
        $speaker = self::query(self::$table)->where(['id' => $data['speaker_id']])->_find();
        !$speaker && exception('音色不存在');
        datetime() > $speaker['expire_time'] && exception('音色已过期');
        $speaker['remain_num'] < 0 && exception('训练次数已用完');
        // 训练
        $speaker_data = [
            'member_id' => $data['member_id'],
            'url' => $data['url'],
            'num' => $speaker['num'] + 1,
            'remain_num' => $speaker['remain_num'] - 1,
        ];

        $appid = "2437967093";
        $token = "lVweTxqK56i0Bho9FVWdZgjIJLyqIiE9";
        $spkId = $speaker["speaker_id"];
        $audioPath = $data['url'];
        $audioPath = str_replace("https://ai.dev.littlegood.cn", ".", $audioPath);
        // 使用示例
        try {

            $voiceClone = new MegaTtsService($appid, $token);
            $voiceClone->train($audioPath, $spkId);  // 上传音频进行训练
//            $voiceClone->getStatus($spkId);  // 查询训练状态
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }


        $speaker_result = self::model()->_update(self::$table, $speaker_data, $data['speaker_id']);
        if (!$speaker_result) {
            Db::rollback();
            exception();
        }
        Db::commit();
        return success();
    }

    /**
     * 新增
     * @param array $data 数据
     * @return mixed
     */
    public static function add($data) {
        Db::startTrans();
        // 音色
//        $data['remain_num'] = 10000;

        $speaker = self::query('speaker')->where(['member_id' => 0, 'is_train' => 0])->_value('speaker_id');
        if(!$speaker){
            Db::rollback();
            exception("没有可以训练的音色");
        }


        // 订单
        $point = SystemConfigService::getDetail('SPEAKER_POINT')['value'] ?: 0;
        $member_point = self::query('member')->where(['member_id' => $data['member_id']])->_value('remain_point');
        $member_point < $point && exception('会员点数不够');


        $appid = "2437967093";
        $token = "lVweTxqK56i0Bho9FVWdZgjIJLyqIiE9";
        $spkId = $speaker;
        $audioPath = $data['url'];
        $audioPath = str_replace("https://ai.dev.littlegood.cn", ".", $audioPath);
        // 使用示例
        try {

            $voiceClone = new MegaTtsService($appid, $token);
            $voiceClone->train($audioPath, $spkId);  // 上传音频进行训练
//            $voiceClone->getStatus($spkId);  // 查询训练状态
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }

        $order_no = OrderService::createOrerNo();
        $order_data = [
            'order_no' => $order_no,
            'member_id' => $data['member_id'],
            'speaker_id' => $speaker,
            'ai_type' => 2,
            'type' => 2,
            'scene_type' => 1,
            'point' => $point,
            'before_point' => $member_point,
            'after_point' => $member_point - $point,
            'remark' => OrderService::getRemark(2, 3),
        ];
        $order_id = self::model()->_insert('order', $order_data);
        if (!$order_id) {
            Db::rollback();
            exception();
        }
        // 用户扣点
        $result = self::model()->_update('member', ['remain_point' => Db::raw("remain_point-{$point}")], ['member_id' => $data['member_id']]);
        if (!$result) {
            Db::rollback();
            exception();
        }
        //绑定音色
        self::model()->_update('speaker', ['member_id' => $data['member_id'],'is_train' => 1], ['speaker_id' => $speaker]);

        Db::commit();
        return success();
    }

    /**
     * 编辑
     * @param array $data 数据
     * @return mixed
     */
    public static function edit($data) {
        $result = self::model()->_update(self::$table, $data, self::ID($data), false);
        !$result && exception();
        return success();
    }

    /**
     * 删除
     * @param array $data 数据
     * @return mixed
     */
    public static function del($data) {
        $result = self::model()->_delete(self::$table, self::ID($data));
        !$result && exception();
        return success();
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListBySelect($data) {
        $list = self::query(self::$table)->_equal('member_id')->where('num', '>', 0)->order('id desc')->_select();
        return $list;
    }

}
